





<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <title>表单设计</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="/static/devtools30/js/formui/dlform.css">
    <link href="/static/devtools30/layui/css/layui.css" rel="stylesheet" />

    <link rel="stylesheet" type="text/css" href="/static/devtools30/js/formui/formdesign.css">
    <script type="text/javascript" src="/static/devtools30/js/formui/formdesign.js"></script>
    <script type="text/javascript" src="/static/devtools30/layui/layui.all.js"></script>
    <script type="text/javascript" src="/static/devtools30/js/formui/Sortable.min.js"></script>
    <script src="/static/devtools30/js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="/static/devtools30/js/formui/formControl.js"></script>
    <script src="/static/devtools30/js/devtoolCommon.js" type="text/javascript"></script>
    <script type="text/javascript" src="/webjars/ace/v1.15.2.20210216/src-noconflict/ace.js"></script>
<!--    <script type="text/javascript" src="/webjars/ace/v1.15.2.20210216/src-noconflict/ext-language_tools.js?v=1"></script>-->
    <title></title>
    <style>
        .dlong_hidden {
            background: #fef0f0 !important;
        }
    </style>
</head>

<body>
<div id="box" class="flex flex-jusity-start">
    <div class="left flex flex-direction-column" id="choose">
        <div class="widget-cate">基础字段</div>
        <ul class="drag_widget_contain">
            <li data-type="input" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-subtraction"></i><span class="textWidth">单行文本</span></a></li>
            <li data-type="textarea" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-align-left"></i><span class="textWidth">多行文本</span></a>
            </li>
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-add-circle-fine"></i><span
                        class="textWidth">计数器</span></a></li> -->
            <li data-type="radio" class="form-edit-widget-label"><a><i class="layui-icon layui-icon-radio"></i><span
                    class="textWidth">单选框组</span></a>
            </li>
            <li data-type="checkbox" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-circle"></i><span class="textWidth">多选框组</span></a>
            </li>
            <!-- <li data-type="date" class="form-edit-widget-label"><a><i class="layui-icon layui-icon-time"></i><span
                        class="textWidth">时间选择器</span></a></li> -->
            <li data-type="date" class="form-edit-widget-label"><a><i class="layui-icon layui-icon-date"></i><span
                    class="textWidth">日期选择器</span></a></li>
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-star"></i><span
                        class="textWidth">评分</span></a></li> -->
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-star"></i><span
                        class="textWidth">颜色选择器</span></a></li> -->
            <li data-type="select" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-triangle-d"></i><span class="textWidth">下拉选择框</span></a></li>
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-play"></i><span
                        class="textWidth">开关</span></a></li> -->
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-slider"></i> <span
                        class="textWidth">滑块</span></a></li> -->
            <li data-type="label" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-survey"></i><span class="textWidth">文字</span></a></li>
            <!-- <li class="form-edit-widget-label"><a><i class="layui-icon layui-icon-fonts-html"></i><span
                        class="textWidth"> HTML</span></a></li> -->
        </ul>
        <div class="widget-cate">高级字段</div>
        <ul>
            <li data-type="fileupload" class="form-edit-widget-label"><a><i
                    class="layui-icon layui-icon-file-b"></i><span class="textWidth">文件</span></a>
            </li>
            <li data-type="editor" class="form-edit-widget-label"><a><i class="layui-icon layui-icon-edit"></i><span
                    class="textWidth">编辑器</span></a>
            </li>
        </ul>

        <div class="widget-cate">布局字段</div>
        <ul>
            <li data-type="grid" class="form-edit-widget-label no-put"><a><i
                    class="layui-icon layui-icon-cols"></i><span class="textWidth">栅格布局</span></a></li>
            <!-- <li class="form-edit-widget-label no-put"><a><i class="layui-icon layui-icon-table"></i><span
                        class="textWidth">表格布局</span></a>
            </li>
            <li class="form-edit-widget-label no-put"><a><i class="layui-icon layui-icon-layer"></i><span
                        class="textWidth">标签页</span></a>
            </li>
            <li class="form-edit-widget-label no-put"><a><i class="layui-icon layui-icon-more"></i><span
                        class="textWidth">分割线</span></a>
            </li> -->
        </ul>
    </div>
    <div class="mid flex flex-direction-column" >

        <div class="el-header btn-bar" style="height: 45px;">
<!--            <span style="color: red" >预览路径: /V_DevtFormDesignEntityController/saveAndUpdatePreview?tempid=表单模版ID</span>-->
            <button onclick="openJson()" type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-release"></i><span>导入JSON</span></button>
            <button type="button" class="el-button el-button--text el-button--medium" onclick="del()">
                <!----><i class="layui-icon layui-icon-delete"></i><span>清空</span></button>
            <button onclick="saveAndPreview()" type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-face-smile-fine"></i><span>保存并预览</span></button>
            <button onclick="preview2()" type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-face-smile-fine"></i><span>新窗口预览</span></button>
            <button onclick="preview1()" type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-face-smile-fine"></i><span>预览</span></button>
            <button onclick="getDesginJSON()" type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-list"></i><span>生成JSON</span></button>
            <button onclick="btn_save()"  type="button" class="el-button el-button--text el-button--medium">
                <!----><i class="layui-icon layui-icon-upload-drag"></i><span>保存</span></button>
            <button onclick="getDesginHtml()" type="button" class="el-button el-button--text el-button--medium">
                <i class="layui-icon layui-icon-list"></i><span>生成代码</span></button>
            <div class="clean"></div>
        </div>
        <!-- <div id="word">从左侧拖拽或点击来添加字段</div> -->
        <div class="el-form" id="fomContent" style="overflow: hidden; overflow-y: auto;">
        </div>
    </div>
    <div class="right" style="overflow: hidden;">
        <form class="layui-form">
            <div class="layui-tab layui-tab-brief" lay-filter="form-attr">
                <ul class="layui-tab-title">
                    <li class="layui-this">字段设置</li>
                    <li>表单设置</li>
                </ul>

                <div class="layui-tab-content" id="tabContent" style="overflow: hidden; overflow-y: auto;">
                    <div class="layui-tab-item layui-show" >
                        <div id="commonDiv" style="display: none;">
                            <div class="layui-form-item">
                                <label class="layui-form-label">控件默认值可以通过下面配置,也可以通过<span style="color: red">mDefaultValue_字段控件ID</span>的参数传递</label>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">ID</label>
                                <div class="layui-input-block">
                                    <input type="text" data-id="id" id="data_id" placeholder="请选择关联表关键字"  autocomplete="off" class="layui-input common_opt" name="ID"  onclick="choseTableAndField()">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">动态SQL<i onclick="layer.tips('SQL格式为:select dm,mc from xxx', this);" class="layui-icon layui-icon-tips"></i></label>
                                <div class="layui-input-block">
                                    <textarea type="text" data-id="datasql" id="data_sql" placeholder="请输入查询SQL" autocomplete="off" class="layui-textarea layui-input common_opt" ></textarea>
                                </div>
                            </div>
                        </div>

                        <div id="columnProperty" >

                        </div>
                    </div>
                    <div class="layui-tab-item">
                        <div class="layui-form-item">
                            <label class="layui-form-label">表单名称</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_name"  autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">表单宽度</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_width"  autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">表单高度</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_height"   autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">控件CSS</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_controlcss"   autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">表单CSS</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_css"   autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">初始化JS  <a href="javascript:tcbjjs('initjs','初始化JS');">弹窗编辑</a></label>
                            <div class="layui-input-block">
                                <textarea type="text" id="initjs"   autocomplete="off" class="layui-textarea layui-input"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">保存JS   <a href="javascript:tcbjjs('savejs','保存JS');">弹窗编辑</a></label>
                            <div class="layui-input-block">
                                <textarea type="text" id="savejs"   autocomplete="off" class="layui-textarea layui-input"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">自定义加载路径
                                请求参数1.tempid 模版ID,2.dataid 数据ID
                                响应JSON {sucess:true,datainfo:{}}
                            </label>
                            <div class="layui-input-block">
                                <input type="text" id="form_loadurl"  autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">自定义保存路径 from提交
                                1、tempid 模版ID , 2、dataid 数据ID  3、strlist 序列化Jsond对象数组,对象key为控件ID</label>
                            <div class="layui-input-block">
                                <input type="text" id="form_saveurl" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </div>

                </div>

            </div>
        </form>
    </div>
</div>

<div id="exportJson" style="display: none;height: 100%;">
    <div class="" style="width:90%;height:80% ;padding: 5%;">
                <textarea autocomplete="off" class="dlong_textarea" type="text" id="txt_json" name="" placeholder="">
                </textarea>
    </div>
    <div style="display: flex;justify-content: center;">
        <div id="import_btn" style="display: none;" >
            <button onclick="btn_importJson()" type="button" class="layui-btn layui-btn-normal layui-btn-sm">导入</button>
        </div>
    </div>
</div>
<div id="previewHTML" style="display: none;height: 100%;">
    <div class="" style="width:90%;height:80% ;padding: 5%;">
                <textarea autocomplete="off" class="dlong_textarea" type="text" id="txt_html" name="" placeholder="">
                </textarea>
    </div>

</div>
<div id="previewDiv" style="display: none;height: 100%;">
    <div style="padding: 20px 40px 0 0;" id="previewMain">

    </div>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
        <button onclick="testSaveData()" type="button" style="background-color:#1890ff;border-radius: 4px;height: 30px;line-height: 30px;padding: 0 10px;" class="layui-btn">确定</button>
        <button type="button" style="border-radius: 4px;height: 30px;line-height: 30px;padding: 0 10px;" class="layui-btn layui-btn-primary">关闭</button>
    </div>

</div>
<div id="tcbjjsDiv" style="display: none;height: 100%;">
    <div style="padding: 0px 10px 0 0;">
        <input type="hidden" id="tcjsid" />
        <textarea autocomplete="off" class="dlong_textarea" type="text" id="txt_js" name="" placeholder="">
        </textarea>

    </div>
    <div style="display: flex;justify-content: center;margin-top: 10px;">
        <button onclick="saveTcJs()" type="button" style="background-color:#1890ff;border-radius: 4px;height: 30px;line-height: 30px;padding: 0 10px;" class="layui-btn">确定</button>
        <button onclick="closeLayer()" type="button" style="border-radius: 4px;height: 30px;line-height: 30px;padding: 0 10px;" class="layui-btn layui-btn-primary">关闭</button>
    </div>
</div>
</body>


<script>
    var height=document.body.clientHeight;
    var width=document.body.clientWidth;
    var $data={};
    $(function () {
        initEvent();
        loadFormDesign();

        $(".mid").height(height)
        $(".right").height(height)

        $("#tabContent").height(height-60)
    })

    var list = [];
    var previewList=[];
    var currentItem=null;

    var currentDrag = {
        type: "",
        label: ""
    };
    Array.prototype.slice.call(document.querySelectorAll(".form-edit-widget-label")).forEach(function (item, ind) {
        // 拖拉之前
        Sortable.create(item, {
                group: {
                    name: 'group_view',
                    pull: 'clone',
                    put: false,

                },
                handle: ".form-edit-widget-label",
                onStart: function (/**Event*/evt) {

                    currentDrag = {
                        type: $(evt.target).attr("data-type"),
                        label: $(evt.target).find("span").text()
                    }
                },
                animation: 150,
                sort: false
            }
        );
    })
    //    拖拉之后
    Sortable.create(document.getElementById("fomContent"), {
        group: {
            name: 'group_view',
            pull: true,
        },
        handle: ".form-edit-widget-label",
        ghostClass: "ghost",
        // 元素从一个列表拖拽到另一个列表
        onAdd: function (/**Event*/evt) {
            if (evt.from.className.indexOf("dlong_col_list") >= 0) {
                //从源布局组件中删除
                //源 grid索引 列索引 项索引 属性
                var fromgridindex=$(evt.from).parents(".dl_widget_view").index();
                var fromcolumnindex=$(evt.from).parent().index();
                var fromcolumn_list_index=evt.oldIndex;
                var fromOption=list[fromgridindex].getOption();
                //拖拽的控件
                var child=fromOption.columns[fromcolumnindex].list[fromcolumn_list_index];
                //从列表中删除拖拽控件
                var newitem=list[fromgridindex].getValue()[fromcolumnindex][fromcolumn_list_index];
                fromOption.columns[fromcolumnindex].list.splice(fromcolumn_list_index,1);

                list.splice(evt.newIndex,0,newitem)
                list[fromgridindex].setOption(fromOption);

                return;
            }
            addCompent(evt,function(el){
                list.splice(evt.newIndex,0,el)
            });

            listenGridDrag();
        },
        // 监听数据拖动后
        onUpdate: function (/**Event*/evt) {

            var newitem= list.slice(evt.oldIndex,evt.oldIndex+1)[0]
            list.splice(evt.oldIndex,1);
            list.splice(evt.newIndex,0,newitem);

        },
        animation: 150
    });

    // 拖动到栅格里
    function listenGridDrag() {
        Array.prototype.slice.call(document.querySelectorAll(".dlong_col_list")).forEach(function (item, ind) {
            Sortable.create(item, {
                group: { name: "group_view", pull: true },
                animation: 150,
                ghostClass: "ghost",
                fallbackOnBody: false,
                onAdd: function (/**Event*/evt) {

                    var isadd=true;
                    if (evt.from.className.indexOf("form-edit-widget-label") < 0) {
                        isadd=false;
                    }
                    var gridindex= $(evt.target).parents(".dl_widget_view").index();//grid 索引
                    var colindex= $(evt.target).parent().index();// grid 列索引
                    var item_index=$(evt.item).index();
                    if(isadd){

                        addCompent(evt,function(el){
                            var oldoption=list[gridindex].getOption();
                            var oldColumn= oldoption.columns[colindex].list;

                            oldColumn.splice(evt.newIndex, 0, el.getOption());
                            list[gridindex].setOption(oldoption);
                            list[gridindex].getValue()[colindex][item_index]._htmlelement.click()
                        });
                    }else{
                        //不是从栅格出来的
                        if (evt.from.className.indexOf("dlong_col_list") < 0) {
                            //找到被拖动的组件索引
                            var fromindex=evt.oldIndex;
                            //删除被拖动的组件list
                            var el=list[fromindex];
                            list.splice(fromindex,1);
                            //找到栅格的列索引
                            list[gridindex].setValue({index:colindex,child:el});

                        }else{
                            //是否同一个grid
                            var sameParent= $(evt.from).parents(".dlong_item")[0] === $(evt.to).parents(".dlong_item")[0]
                            //源 grid索引 列索引 项索引 属性
                            var fromgridindex=$(evt.from).parents(".dl_widget_view").index();
                            var fromcolumnindex=$(evt.from).parents(".dlong_col").index();
                            var fromcolumn_list_index=evt.oldIndex;
                            var fromOption=list[fromgridindex].getOption();
                            //拖拽的控件
                            var child=fromOption.columns[fromcolumnindex].list[fromcolumn_list_index];
                            //从列表中删除拖拽控件
                            fromOption.columns[fromcolumnindex].list.splice(fromcolumn_list_index,1)


                            var newOption=list[gridindex].getOption();
                            var tocolumn_list_index=$(evt.item).index();
                            //刷新源grid
                            if(!sameParent){
                                list[fromgridindex].setOption(fromOption);
                            }else{
                                newOption=fromOption;
                            }

                            newOption.columns[colindex].list.splice(tocolumn_list_index,0,child);
                            //重新渲染
                            list[gridindex].setOption(newOption);
                            initControl(list[gridindex].getValue()[colindex].slice(tocolumn_list_index,tocolumn_list_index+1)[0])
                        }

                        list[gridindex].getValue()[colindex][item_index]._htmlelement.click()
                    }

                    listenGridDrag();


                },
                // 监听数据拖动后
                onUpdate: function (/**Event*/evt) {
                    var gridindex= $(evt.target).parents(".dl_widget_view").index();//grid 索引
                    var colindex= $(evt.target).parent().index();// grid 列索引
                    var oldoption=list[gridindex].getOption();
                    var oldColumn= oldoption.columns[colindex].list;
                    var olditem=oldColumn.slice(evt.oldIndex,evt.oldIndex+1)[0];
                    oldColumn.splice(evt.oldIndex, 1);
                    oldColumn.splice(evt.newIndex, 0, olditem);
                    list[gridindex].setOption(oldoption);

                },
                onEnd: function (/**Event*/evt) {

                    listenGridDrag();

                },
            });
        })
    }

    //拖拽新增组件
    function addCompent(evt,callback) {

        var el;
        el = document.createElement("div")
        if (currentDrag.type == "grid") {
            el.className = "dl_widget_view";


        } else {
            el.className = "dl_widget";

        }
        // 替换原来的节点
        evt.target.replaceChild(el, evt.item);
        var input1 = formDesign.render(el, {
            label: currentDrag.label,
            type: currentDrag.type,
        })
        //list.push(input1)

        callback&&callback(input1);
    }
    // 点击出现边框
    function initEvent() {
        $("#fomContent").delegate(".dl_widget,.dl_widget_view", "click", function (el) {

            event.stopPropagation()
            event.preventDefault()

            var sortBtn = '<div class="sotrBtn"><i class="layui-icon layui-icon-addition form-edit-widget-label"></i></div>'
            var del = '<div class="del_ele"> <!--<i class="layui-icon layui-icon-templeate-1" onclick="cloneEl(this)"></i>--><i class="layui-icon layui-icon-delete" onclick="delEl(this)"></i> </div>';
            $('.active').removeClass('active')
            $(this).addClass('active');
            $('.del_ele,.sotrBtn').remove()
            $(this).append(del, sortBtn);

            var gridindex= $(this).parents(".dl_widget_view").index();//grid 索引
            var colindex= $(this).parents(".dlong_col").index();// grid 列索引
            var itemindex=$(this).index();
            if(gridindex>=0){
                initControl(list[gridindex].getValue()[colindex].slice(itemindex,itemindex+1)[0])
            }
            else{
                evenClick(itemindex);
            }
            return false;
        })
        //固定控件属性
        $('.common_opt').off('input').on('input', function (e) {
            var option= currentItem.getOption();
            var key=$(this).attr("data-id");
            option[key]=$(this).val();
            currentItem.setOption(option);
            refreshGrid();
        })

    }
    // 点击复制节点
    function cloneEl(el) {
        // var inde = $(el).parent().parent();
        // inde.clone(true).insertBefore(inde);
    }
    // 点击删除节点
    function delEl(el) {

        //找到索引
        var el_item=$(el).parent().parent();
        var itemIndex=$(el_item).index();
        var gridIndex=$(el_item).parents(".dl_widget_view").index();
        //执行组件内删除  list[0].remove()
        if(gridIndex>=0){

            var colindex=$(el).parents(".dlong_col").index();

            var newoption=list[gridIndex].getOption();
            newoption.columns[colindex].list.splice(itemIndex,1);
            list[gridIndex].setOption(newoption);
            listenGridDrag();
        }else{
            list.splice(itemIndex,1);
        }
        $(el_item).remove();
    }
    // 清空
    function del() {
        document.getElementById("fomContent").innerHTML = "";
        list = []
    }



    // 组件点击事件
    function evenClick(index) {
        var item = list[index]
        initControl(item);


    }
    //初始化控件事件
    function initControl(item) {
        $(".common_opt").val("");
        $(".common_opt").each(function(data){
            var key=$(this).attr("data-id");
            if(key=="datasql"){
                $(this).val(item.getOption()["datasql"]||"");
            }
            if(key=="id"){
                $(this).val(item.getOption()["id"]||"");
            }

        })
        //给公共控件属性赋值
        $("#commonDiv").show();

        var option = item.getOption();
        currentItem=item;
        //初始化
        var controll = formControl.createControl("#columnProperty", item.getConfig());
        //监听
        controll.listenEvent(function (key, value) {
            if (option[key] == value) {
                return;
            }
            option[key] = value;
            item.setOption(option);
            refreshGrid();
            listenGridDrag();
        })
    }

    //单独处理grid内控件刷新问题
    function refreshGrid(){
        list.forEach(function(item){
            var option=item.getOption();
            if(option.type=="grid"){
                var child=item.getValue();
                var columns=option.columns;
                for(var i=0;i<child.length;i++){
                    for(var j=0;j<child[i].length;j++){
                        columns[i].list[j]=child[i][j].getOption()
                    }
                }
                // item.setOption(option);
            }

        })
    }

    //导出json
    function getDesginJSON(){
        var allJson=getFormJson();

        openJson(allJson);

    }
    //获取设计表单json
    function getFormJson(){
        var jsonlist=[];
        list.forEach(function(item){
            jsonlist.push(item.getOption())
        })
        var allJson={
            list:jsonlist,
            config:{
                name:$("#form_name").val(),
                width:$("#form_width").val(),
                height:$("#form_height").val(),
                controlCss:$("#form_controlcss").val(),
                formCss:$("#form_css").val(),
                initjs:$("#initjs").val(),
                savejs:$("#savejs").val(),
                formloadurl:$("#form_loadurl").val(),
                formsaveurl:$("#form_saveurl").val(),
            }
        }
        return allJson;
    }
    //打开json弹出框
    function openJson(jsonlist){
        layer.open({
            title:"JSON",
            type: 1,
            area: ['600px', '500px'],
            content: layui.$('#exportJson')
        });
        if(jsonlist){

            $("#txt_json").val(JSON.stringify(jsonlist));
            $("#import_btn").hide();
        }else{
            $("#txt_json").val("");
            $("#import_btn").show();
        }

    }

    function loadFormDesign(){
        $("#form_width").val("900")
        $("#form_height").val("600")
        var jsonstr=unescape('[(${loadFormJson})]');
        if(!jsonstr){
            return;
        }
        var allJson=JSON.parse(jsonstr);
        if(allJson.config){
            $("#form_name").val(allJson.config.name),
                $("#form_width").val(allJson.config.width),
                $("#form_height").val(allJson.config.height),
                $("#form_controlcss").val(allJson.config.controlCss),
                $("#form_css").val(allJson.config.formCss),
                $("#savejs").val(allJson.config.savejs),
                $("#initjs").val(allJson.config.initjs),
                $("#form_loadurl").val(allJson.config.formloadurl),
                $("#form_saveurl").val(allJson.config.form_saveurl)
        }

        renderByJson(allJson.list);
        layer.closeAll();
    }

    function btn_importJson(){
        var jsonstr=$("#txt_json").val();
        if(!jsonstr){
            return;
        }
        var allJson=JSON.parse(jsonstr);
        if(allJson.config){
            $("#form_name").val(allJson.config.name);
            $("#form_width").val(allJson.config.width);
                $("#form_height").val(allJson.config.height);
                $("#form_controlcss").val(allJson.config.controlCss);
                $("#form_css").val(allJson.config.formCss);
                $("#initjs").val(allJson.config.initjs);
            $("#savejs").val(allJson.config.savejs);
        }

        renderByJson(allJson.list);
        layer.closeAll();
    }
    //从json生成设计
    function renderByJson(jsonList){
        if(!jsonList||jsonList.length<=0){
            return;
        }
        del();
        var fristNode= document.getElementById("fomContent");
        jsonList.forEach(function(item){
            var el = document.createElement("div")
            if (item.type == "grid") {
                el.className = "dl_widget_view";
            } else {
                el.className = "dl_widget";
            }
            fristNode.appendChild(el);
            var input1 = formDesign.render(el, item);
            list.push(input1);
        })
        listenGridDrag();
        listToData(list);
    }

    function saveAndPreview() {

        var allJson=getFormJson();
        if(!allJson.list||allJson.list.length<=0){
            return;
        }
        var formConfig=allJson.config;
        var fwidth=formConfig.width||(width-20);
        var fheight=(formConfig.height)||height-40;
        btn_save(function(){
            var url="/V_DevtFormDesignEntityController/saveAndUpdatePreview?tempid=[(${pid})]";
            dlCommon.layeropen(fwidth,fheight,"表单预览",url);
        });

    }

    function preview2(){
        var url="/V_DevtFormDesignEntityController/saveAndUpdatePreview?tempid=[(${pid})]";
        window.open(url);
    }

    function preview1(){
        var allJson=getFormJson();
        if(!allJson.list||allJson.list.length<=0){
            return;
        }
        var formConfig=allJson.config;
        var fwidth=formConfig.width||(width-20);
        var fheight=(formConfig.height)||height-40;
        previewList=[];
        layer.open({
            title:"预览",
            type: 1,
            area: [fwidth+'px', fheight+'px'],
            content: layui.$('#previewDiv')
        });

        setPreHTML(allJson);
        listToData(previewList);
    }
    //预览 保存测试数据
    function testSaveData(){
        var strlist=[];
        try{
            previewList.forEach(function(item){
                if(item.getOption().type=="grid"){
                    item.childArray.forEach(function(child){
                        var option=child.getOption();
                        if(child.getValue()==""&&option.required){
                            throw new Error(option.requiredMessage||(option.label+"必填"))
                        }

                        strlist.push(JSON.stringify({id:option.id,value:child.getValue()}) );
                    })
                }else{
                    var option=item.getOption();
                    if(item.getValue()==""&&option.required){

                        throw new Error(option.requiredMessage||(option.label+"必填"))
                    }
                    strlist.push(JSON.stringify({id:option.id,value:item.getValue()}));
                }

            })
        }catch(e){
            alert(e.message);
            return;
        }

        alert(strlist.join("\n"));
    }
    function listToData(datalist){
        datalist.forEach(function(item){
            if(item.getOption().type=="grid"){
                item.childArray.forEach(function(child){
                    var option=child.getOption();
                    $data[option.id]=child;
                })
            }else{
                var option=item.getOption();
               $data[option.id]=item;
            }
        })
    }
    //保存设计配置
    function btn_save(callback){
        var jsonOpt=getFormJson();//配置json
        //用于服务端的独特属性
        var postlist=[];
        list.forEach(function(item){
            if(item.getOption().type=="grid"){
                item.childArray.forEach(function(child){
                    var option=child.getOption();
                    if(option.id){
                        postlist.push({
                            fieldid:option.id,
                            datasql:option.datasql||""
                        });
                    }
                })
            }else{
                var option=item.getOption();
                if(option.id){
                    postlist.push({
                        fieldid:option.id,
                        datasql:option.datasql||""
                    });
                }
            }
        })
        var data={
            jsonopt:JSON.stringify(jsonOpt),
            postlist:JSON.stringify(postlist)
        }
        console.log(data)
        //保存数据到服务端
        dlCommon.post("/DevtFormDesignEntityController/toSave?pid=[(${pid})]",data,function(res){
            dlCommon.layerMsg(res.msg);
            callback&&callback()
        },true)

    }

    function choseTableAndField(){
        var url="/V_DevtFormDesignEntityController/toChoseTableAndFieldPage?tempid=[(${pid})]";
        dlCommon.layeropen(800,600,"字段选择",url)
    }

    function setValueOfId(tableCode,fieldid){
        if(tableCode!=''&&fieldid!=''){
            $('#data_id').val(tableCode+"@"+fieldid);
        }else {
            $('#data_id').val("");
        }

        var option= currentItem.getOption();
        option["id"]=$("#data_id").val();
        currentItem.setOption(option);
        refreshGrid();
    }
    //生成html代码
    function getDesginHtml(){
        //预览html
        setPreHTML();
        var body=document.getElementById("previewMain").innerHTML;
        var header='<!DOCTYPE html> \n';
        header+='<html xmlns:th="http://www.w3.org/1999/xhtml">\n';
        header+='<head>\n';
        header+='<link rel="stylesheet" href="/static/devtools30/js/formui/dlform.css">\n'
        header+='<link rel="stylesheet" href="/static/devtools30/layui/css/layui.css">\n'
        header+='<script type="text/javascript" src="/static/devtools30/layui/layui.all.js"><\/script>\n'
        header+='<style>'
        header+='.dlong_hidden {';
        header+='background: #fef0f0 !important;';
        header+='display: none;';
        header+='}';
        header+='<\/style>\n';
        var html=header;
        html+='<body>\n';
        html+='<div class="main">\n'+body+'\n</div>\n';
        html+='<\/body>\n';
        html+='<\/html>\n';
        layer.open({
            title:"HTML",
            type: 1,
            area: ['600px', '500px'],
            content: layui.$('#previewHTML')
        });
        $("#txt_html").val(html)
        //console.log(html);
    }
    function setPreHTML(allJson){
        if(!allJson){
            allJson=getFormJson();
            if(!allJson.list||allJson.list.length<=0){
                return;
            }
        }
        formConfig=allJson.config;
        document.getElementById("previewMain").innerHTML="";
        if(formConfig.formCss){
            document.getElementById("previewMain").style.cssText=formConfig.formCss;
        }
        var fristNode= document.getElementById("previewMain");
        allJson.list.forEach(function(item){
            var el = document.createElement("div")
            el.style.cssText=formConfig.controlCss||"padding-bottom:15px;";
            fristNode.appendChild(el);
            var input1 = formDesign.render(el, item);
            previewList.push(input1);
        })
        $("#previewMain .dl_widget").removeClass("dl_widget")
        $("#previewMain .dlong_col_list").removeClass("dlong_col_list");
    }
</script>

<script>
    var editorThis;
    var thisintdex;
    function tcbjjs(jsid,title){
        layui.$('#tcjsid').val(jsid);
        var allJson=getFormJson();
        if(!allJson.list||allJson.list.length<=0){
            return;
        }
        var formConfig=allJson.config;
        var fwidth=formConfig.width||(width-20);
        var fheight=(formConfig.height)||height-40;
        thisintdex=layer.open({
            title:title,
            type: 1,
            area: [fwidth+'px', fheight+'px'],
            content: layui.$('#tcbjjsDiv')
        });

        if(!editorThis){
            //引入语言工具
            ace.require("ace/ext/language_tools");
            editorThis = ace.edit(('txt_js'));
            //选择主题
            // editorThis.setTheme("ace/theme/twilight");
            editorThis.setTheme("ace/theme/eclipse");

            //选择语言
            // editorThis.session.setMode("ace/mode/javascript");
            editorThis.session.setMode("ace/mode/javascript");
            //各项设置
            editorThis.setOptions({
                enableBasicAutoCompletion : true,
                enableSnippets : true,
                enableLiveAutocompletion : true,
                maxLines:1300
            });
        }
        editorThis.setValue(layui.$('#'+jsid).val())
        if(layui.$('#'+jsid).val().length==0||editorThis.session.getLength()<3){
            editorThis.setValue(editorThis.getValue()+"\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
        }
    }

    function saveTcJs(){
        var jsid = layui.$('#tcjsid').val();
        layui.$('#'+jsid).val("\r\n\r\n"+editorThis.getValue().trim()+"\r\n\r\n\r\n");
        closeLayer();
    }

    function closeLayer(){
        thisintdex&&layer.close(thisintdex)
    }
</script>
</html>